//
// Created by tanzx on 2023/12/8.
//

#include "test_thread.h"
#include <cstdio>
#include <unistd.h>
#include <pthread.h>

static pthread_key_t  key;

void delete_func(int t)
{
    printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);
}

void * child1(void *arg)
{
    pthread_t tid = pthread_self();
    printf("thread %d enter\n",tid);
    pthread_setspecific(key,(void *)tid);
    sleep(2);
    printf("thread %d returns %d and key %d\n",tid,pthread_getspecific(key),key);
    sleep(5);
}

void * child2(void *arg)
{
    pthread_t tid = pthread_self();
    printf("thread %d enter\n",tid);
    pthread_setspecific(key,(void *)tid);
    sleep(1);
    printf("thread %d returns %d and key %d\n",tid,pthread_getspecific(key),key);
    sleep(5);
}


void func1(int &a) {
    std::thread::id currentThreadId = std::this_thread::get_id();
    //cout << "func start Current Thread ID: " << currentThreadId << endl;
    for (int i = 0; i < 100 * 1000; i++) {
        a += 1;
    }
    std::cout << "func end Current Thread ID: " << currentThreadId << std::endl;
}

void testThread() {
    int a = 0;
    std::thread t1(func1, std::ref(a));
    std::thread t2(func1, std::ref(a));
    t2.join();
    std::cout << "a=" << a << '\n';
    a = 0;
    std::thread t3(func1, std::ref(a));
    std::thread t4(func1, std::ref(a));
    //t3.join();
    t4.join();
    std::cout << "a2=" << a << std::endl;
}

void test_pthread_key() {
    pthread_t tid1, tid2;
    printf("this is main thread\n");
    //第一个参数就是 pthread_key_t 变量；
    // delete_func：第二个参数是一个清理函数，用来在线程释放该线程存储的时候被调用
    pthread_key_create(&key, (void (*)(void *)) delete_func);
    pthread_create(&tid1, NULL, child1, NULL);
    pthread_create(&tid2, NULL, child2, NULL);
    sleep(10);
    pthread_key_delete(key);
    printf("main thread exit\n");
}